import { brain_space_fact, delete_brain_space_fact } from '@/services/ant-design-pro/brainSpace';
import { connect } from '@umijs/max';
import { Empty, message, Pagination, Select } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import LongDocItem from '../LongDocItem';
import './index.less';
const dayjs = require('dayjs');

// 有历史记录组件
const AdministrativeKnowledge: React.FC<any> = forwardRef((props: any, ref) => {
  const tagKey = useRef(''); // tag的key
  const [loaded, setLoaded] = useState(false); // 加载完成
  const [totalCount, setTotalCount] = useState(0); // 文章总数
  const [dataList, setDataList] = useState<any[]>([]); // 文档列表
  const [typeOptions, setTypeOptions] = useState<any[]>([]); // 类型列表
  //分页默认值，
  const [pageOption, setPageOption] = useState({
    page: 1, //当前页为1
    per_page: 10, //一页10行
  });

  useImperativeHandle(ref, () => ({
    reloadData: () => {
      setPageOption({
        page: 1, //当前页为1
        per_page: 10, //一页10行
      });

      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      loadMoreData(1, 10);
    },
  }));

  // 时间格式
  const formatAtTime = (timestamp: any) => {
    return dayjs(timestamp).format('YYYY/MM/DD');
  };

  // 加载数据
  const loadCognitionTypes = async () => {
    const data: any = [{ value: '', label: '全部类型' }];
    props.spaceModel.cognitionTypes.forEach((v: any) => {
      if (v.name === 'fact' && v.second_class_list && v.second_class_list.length) {
        v.second_class_list.forEach((c_v: any) => {
          const obj: any = {
            value: c_v,
            label: c_v,
          };
          data.push(obj);
        });
      }
    });
    setTypeOptions(data);
  };
  // 加载数据
  const loadMoreData = async (page: number, per_page: number) => {
    const params: any = { page, per_page };
    if (tagKey.current) {
      params.tag = tagKey.current;
    }
    const res = await brain_space_fact(params);
    if (res.code === 0) {
      if (res.data.data && res.data.data.length) {
        const { total_count, data } = res.data;
        data.forEach((v: any) => {
          v.release_time = v.updated_at ? formatAtTime(v.updated_at) : '-';
          v.deleteShow = false;
          v.showTag = true;
        });
        setTotalCount(total_count);
        setDataList(data);
      }
      setLoaded(true);
    } else {
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
  };

  // 类型切换
  const handleTypeChange = (value: string) => {
    tagKey.current = value;
    setPageOption({
      page: 1,
      per_page: 10,
    });
    setTotalCount(0);
    loadMoreData(1, 10);
  };

  // 删除
  const handleDelete = async (item: any) => {
    const res = await delete_brain_space_fact(item.id);
    if (res.code === 0) {
      // 删除成功
      message.open({
        type: 'success',
        content: '删除成功',
      });
      loadMoreData(pageOption.page, pageOption.per_page);
    } else {
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
  };

  //当翻页时，改变当前为第current页，current和size这两参数是onChange API自带的，会帮你算出来你现在在第几页，这一页有多少行数据。
  const paginationChange = async (current: number, size: number) => {
    //前面用到useState
    setPageOption({
      page: current, //当前所在页面
      per_page: size, //一页有几行
    });

    loadMoreData(current, size);
  };

  //page变动时触发请求
  useEffect(() => {
    loadMoreData(pageOption.page, pageOption.per_page);
    loadCognitionTypes();
  }, []);

  return (
    <div className="AdministrativeKnowledge p-r">
      <div className="page-container">
        <div className="statefulComponent">
          <div className="flex-acen-sb">
            <div className="f-s-20 doc-title">行政局知识空间</div>
            <div>
              <Select
                defaultValue={tagKey.current}
                style={{ width: 120 }}
                onChange={handleTypeChange}
                options={typeOptions}
              />
            </div>
          </div>
          {dataList.length === 0 && loaded && (
            <Empty className="empty" image={Empty.PRESENTED_IMAGE_SIMPLE} />
          )}
          {dataList.length > 0 && (
            <div className="top-doc-box other-doc">
              <div className="docTypeListBox">
                {dataList.map((item: any) => {
                  return (
                    <LongDocItem
                      key={item.id}
                      item={item}
                      boxType="long"
                      type="otherDoc"
                      titleType="tag"
                      deleteData={handleDelete}
                    />
                  );
                })}
              </div>
            </div>
          )}
          {/* 分页 */}
          {dataList.length > 0 && (
            <div className="flex-jcon-end m-t-10">
              <Pagination
                current={pageOption.page}
                defaultCurrent={1}
                pageSize={pageOption.per_page}
                total={totalCount}
                showSizeChanger={false}
                onChange={paginationChange}
              />
            </div>
          )}
        </div>
      </div>
    </div>
  );
});
export default connect(({ spaceModel }) => ({ spaceModel }), null, null, { forwardRef: true })(
  AdministrativeKnowledge,
);
